<?php
/**
 * Created by PhpStorm.
 * User: giozola
 * Date: 2018/8/23
 * Time: 16:02
 */

namespace addons\hlapp\controller;


use app\common\controller\Addon;
use think\facade\Session;

class Common extends Addon
{
    static public $fileDir = "uploadFile";
    /**
     * 通用变量
     * @param string $template
     * @param array $vars
     * @param array $replace
     * @param array $config
     * @return mixed|void
     */
    public function fetch($template = '', $vars = [], $replace = [], $config = []){
        $this->assign("mfix","mid/".Session::get("mid"));
        parent::fetch($template, $vars, $replace, $config);
    }

    //获取 access_token
//    public function getAccessToken(){
//        $mp_options = Session::get("mp_options");
//        $appid = $mp_options["appid"];
//
//        // 查看缓存中是否有数据
//        $cache = new FileCache();
//        $access_token = $cache->get("access_token_".$appid);
//        if(!$access_token){
//            $appsecret = $mp_options["appsecret"];
//            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
//            $res = json_decode(self::actionCurlRequest($url));
//            \Log::INFO("请求返回数据为:".json_encode($res));
//            $access_token = $res->access_token;
//            //时间默认5分钟
//            $cache->set("access_token_".$appid,$access_token,300);
//        }
//        return $access_token;
//    }

    /**
     * 发送模板消息
     * @param $open_id  用户公众号的openId
     * @param $template_id  模板id
     * @param $jumpUrl  消息跳转的url
     * @param $data 模板消息内容
     * @return mixed    返回参数
     */
//    public function sendTemplateMessage($open_id,$template_id,$jumpUrl,$data){
//        $token = self::getAccessToken();
////        $open_id="oKUSB5zkKg54qM_KxM_w1k3MyQqc";
////        $template_id = "m7AdsX0gc59aMM-ldl-Bw4c-HcBPBUgF7IjYwHiOvsc"; //模板id
//        $postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
//        //设置发送的消息
//        $message = [
//            'touser'=>$open_id,
//            'template_id'=>$template_id,
//            'url'=>$jumpUrl,
//            'data'=>$data
//        ];
//        $data = json_encode($message);
//
//        // 发送
//        $res = self::actionCurlRequest($postUrl,$data);
//        \Log::INFO("发送模板消息返回：".json_encode($res,JSON_UNESCAPED_UNICODE));
//        return $res;
//    }

    //curl请求，支持post和get
//    public function actionCurlRequest($url,$data=null){
//        $curl = curl_init();
//        curl_setopt($curl,CURLOPT_URL,$url);
//        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
//        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
//        if(!empty($data)){
//            curl_setopt($curl,CURLOPT_POST,1);
//            curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
//        }
//
//        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
//        $output = curl_exec($curl);
//        curl_close($curl);
//        return $output;
//    }
    //post json
//    function http_post_data($url, $data_string) {
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_POST, 1);
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
//        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
//                "Content-Type: application/json; charset=utf-8",
//                "Content-Length: " . strlen($data_string))
//        );
//        ob_start();
//        curl_exec($ch);
//        $return_content = ob_get_contents();
//        ob_end_clean();
//        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//        return array($return_code, $return_content);
//    }

    /**
     * 分页页面
     */
    public function paginationPage(){
        $pageHtml = '<div class="page" v-if="pageCount !=\'\' && pageCount > 0">
        <div>
          <a class="prev" @click="getListPage(1)">首页</a>
          <a class="num" v-if="pageIndex > 1" @click="getListPage(pageIndex - 1)">上一页</a>
          <a class="num" v-if="pageIndex-2 > 1" @click="getListPage(pageIndex - 2)">{{pageIndex-2}}</a>
          <a class="num" v-if="pageIndex-1 > 1" @click="getListPage(pageIndex - 1)">{{pageIndex-1}}</a>
          <span class="current">{{pageIndex}}</span>
          <a class="num" v-if="pageIndex*1+1 < pageCount"
             @click="getListPage(pageIndex*1+1)">{{pageIndex*1+1}}</a>
          <a class="num" v-if="pageIndex*1+2 < pageCount"
             @click="getListPage(pageIndex*1+2)">{{pageIndex*1+2}}</a>
          <a class="num" v-if="pageIndex < pageCount" @click="getListPage(pageIndex*1 + 1)">下一页</a>
          <a class="next" @click="getListPage(pageCount)">末页</a>
        </div>
      </div>';
        $this->assign('pageHtml',$pageHtml);
    }

    /**
     * 获取第几周 向下取整
     * @param $beginTime 时间戳
     * @param $endTime 时间戳
     * @return float|int|void
     */
    public function getWeeks($beginTime,$endTime){
        $timeStamp = $endTime - $beginTime;
        $days =  (int) $timeStamp/86400;
        return (int)($days/7);
    }

    /**
     * 获取一年的第几个周
     */
    public function getWeekOfYear($time){
        return date('W',$time);
    }

    /**
     * 本周开始时间戳
     * @param $time 时间戳
     * @return false|int
     */
    public function getWeekStartTime($time){
        return strtotime(date('Y-m-d', strtotime("this week Monday", $time)));
    }
    // 获取周数
    public function getWeeksBystamp($beginTime,$endTime){
        $timeStamp = $endTime - $beginTime;
        $days =  (int) $timeStamp/86400;
        if ($days %7 == 0){
            return $days /7;
        }else{
            return (int)($days /7)+1;
        }
    }
    /**
     * 导出excel表格
     * @param $fileName
     * @param $tHead
     * @param $tData
     * @return string
     */
    public function exportExcel($fileName,$tHead,$tData)
    {
        $fileName = $fileName.date("YmdH").".xls";
        $filePath = self::$fileDir."/".$fileName;
        // 实例化PHPExcel
        $PHPExcelObj = new \PHPExcel();
        // 设置excel属性
        $PHPExcelObj->getProperties()->setCreator("JAMES")
            ->setlastModifiedBy("JAMES")
            ->setTitle("zltrans")
            ->setSubject("Dorder")
            ->setDescription("Dorder List")
            ->setKeywords("Dorder")
            ->setCategory("Test result file");
        if ($tHead && count($tHead) > 0) {
            $i = 65;
            foreach($tHead as $key=>$value){
//                Log::write(chr($i).'1'."    ".$key);
                $PHPExcelObj->setActiveSheetIndex(0)->setCellValue(chr($i).'1', $key);
                $i++;
            }
            $c = 1;
            foreach ($tData as $key => $value) {
                $c++;
                $i = 65;
                foreach($tHead as $Hkey=>$Hvalue){
                    $PHPExcelObj->setActiveSheetIndex(0)->setCellValue(chr($i).$c, $value[$Hvalue]);//编号
                    $i++;
                }
            }
        }else{
            Log::write("表头数据传参出错");
        }
        // 将Excel文件保存到框架指定目录
//        import("Org.Util.PHPExcel.IOFactory");
        $ObjWriter = \PHPExcel_IOFactory::createWriter($PHPExcelObj, 'Excel2007');
        $filelName = iconv('utf-8', 'utf-8', $fileName); //利用Iconv函数对文件名进行重新编码
        $ObjWriter->save($filePath);
        ob_end_clean();
        return $filePath;
    }

}